﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Castle.DynamicProxy;
using JavaNET.context;
using JavaNET.listener;
using javanet.JavaNETCommunicationProxyReference;
using System.Diagnostics;

namespace JavaNET.communication
{
    public class JavaNETCommunicationProxyFactory
    {
        private static Type listenerClass;
        private static String remoteAddress;

        public static Object WrapAs(Type type)
        {
            var generator = new ProxyGenerator();
            var proxy = generator.CreateInterfaceProxyWithoutTarget(type, new JavaNETCommunicationProxy());
            return proxy;
        }

        public static Object WrapAs(Type type, JavaNETFacadeContext facadeContext)
        {
            var generator = new ProxyGenerator();
            var proxy = generator.CreateInterfaceProxyWithoutTarget(type, new JavaNETCommunicationProxy(facadeContext));
            return proxy;
        }

        public static T WrapAs<T>() where T : class
        {
            var proxy = WrapAs(typeof(T));
            return (T)proxy;
        }

        public static void registerListener<T>() where T : JavaNETCommunicationListener
        {
            listenerClass = typeof(T);
        }

        public static void registerRemoteAddress(String address)
        {
            remoteAddress = address;
        }

        public static JavaNETCommunicationListener createRegisteredListener()
        {
            if (listenerClass == null)
                return null;
            JavaNETCommunicationListener listener = (JavaNETCommunicationListener)Activator.CreateInstance(listenerClass);
            return listener;
        }

        private static JavaNETCommunicationProxyClient proxyClient;
        public static JavaNETCommunicationProxyClient getJavaNETCommunicationProxyClient()
        {
            if (proxyClient == null)
            {
                Debug.WriteLine("creating JavaNETCommunicationProxyClient.");
                proxyClient = new JavaNETCommunicationProxyClient("JavaNETCommunicationProxyPort", remoteAddress);
            }
            return proxyClient;
        }

    }

}